import axios from 'axios'
import qs from 'qs';
import {baseUrl,isMock} from "../common/base";
import {Storage} from "./storage"
import Vue from 'vue'
import router from '../router'
import Raven from 'raven-js';

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

axios.interceptors.response.use(null,error => {
  // axiosHelper.error(error)
  Raven.captureException(error)
  return Promise.reject(error)
})
export const Ajax = {
  urlInit(url){
    let arr = url.split("?");
    if (arr.length > 1) {
      url += `&t=${new Date().getTime()}`
    } else {
      url += `?t=${new Date().getTime()}`
    }
    return  (baseUrl + url);

  },
  codeInit(res) {

  },
  get(url, cb, opt) {
    url = this.urlInit(url);
    let _this = this;
    axios.get(url, {
      params: opt,
      headers:{
        Authorization:this.getToken(),
      }
    })
      .then(function (res) {
        // console.log(res)
        _this.resultDeal(cb,res,_this);
      })
    .catch(function (err) {
     console.log("err",err)
    });
  },
  post(url, opt, cb,requestBody) {//如果是post请求，且参数是放在body，requestBody传1
    url =this.urlInit(url);
    let _this = this;
    if(requestBody){
    }else{
      opt=qs.stringify(opt);
    }
    axios.post(url, opt,{
      headers:{
        Authorization:this.getToken()
      }
    }).then(function (res) {
      _this.resultDeal(cb,res,_this);
      })
    .catch(function (err) {
      Vue.$vux.toast.text("网络错误，请重新请求", 'center');
      // Msg('error')
    });
  },
  jsonpost(url,opt,cb,requestBody){
    url =this.urlInit(url);
    let _this = this;
    // if(requestBody){
    // }else{
    //   opt=qs.stringify(opt);
    // }
    axios.post(url, opt,{
      headers:{
        Authorization:this.getToken(),
        "Content-Type":"application/json;charset=UTF-8"
      }
    }).then(function (res) {
      _this.resultDeal(cb,res,_this);
    })
      .catch(function (err) {
        Vue.$vux.toast.text("网络错误，请重新请求", 'center');
        // Msg('error')
      });
  },
  delete(url, cb, opt) {
    url = this.urlInit(url);
    let _this = this;
    axios.delete(url, {
      params: opt,
      headers:{
        Authorization:this.getToken()
      }
    })
      .then(function (res) {
        _this.resultDeal(cb,res,_this);
      })
      .catch(function (err) {
        console.log("err",err)
      });
  },
  resultDeal(cb,res,_this){
    if(res.data.code==10004||res.data.code==10003){
      Vue.$vux.toast.text("请先登入", 'center');
      Storage.remove("token")
      setTimeout(()=>{
        // if(Storage.get('isInApp')) {
        //   this.$callJava({code:1012,quick :true})
        // }else{
          router.push({path: '/login',query:{sellerId:Storage.get('sellerId')}})
        // }-
      },1000)
    }else{
      cb && cb(res.data)
    }
  },
  getToken(){
    if(Storage.get("token")!=null&&Storage.get("token")!='null'){
      return Storage.get("token")
    }
    return '';
    // return "test";
  }

}
